package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"week_exam_2_3/api/request"
	"week_exam_2_3/internal/bao"
	"week_exam_2_3/internal/model"
	"week_exam_2_3/pkg"
)

func Login(context *gin.Context) {
	var login request.LoginRequest
	if err := context.ShouldBind(&login); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	var User model.User
	User.Password = pkg.MD5(login.Password)
	User.Account = login.Account
	err := bao.FundOnce(&User)
	if err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	if User.ID == 0 {
		context.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": "账号或密码错误",
		})
		return
	}
	set, _ := json.Marshal(User)
	handler, err := pkg.TokenHandler(string(set))
	if err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "ok",
		"data":    handler,
	})

}
